package com.tkm.builtinTypes.eg

//  1+2 -> calc -> 3
//  4-2 -> calc -> 2
//  3*4 -> calc -> 12
//  9/3 -> calc -> 3
fun main() {
    println("1+2=${calc("1+2")}")
    println("4-2=${calc("4-2")}")
    println("3*4=${calc("3*4")}")
    println("9/3=${calc("9/3")}")
}

fun calc(exp: String): Int {
    if (exp.length < 3) {
        throw IllegalArgumentException("exp must not be < 3")
    }

    val opMap = mapOf(
        "+" to ::plus,
        "-" to ::minus,
        "*" to ::multi,
        "/" to ::div
    )

    val op = exp[1].toString()
    val arg1 = exp[0].toString().toInt()
    val arg2 = exp[2].toString().toInt()
    val opFun = opMap[op] ?: throw IllegalArgumentException("op $opMap is null")
    val res = opFun.invoke(arg1, arg2)
    return res
}

//  定义四则运算
fun plus(a: Int, b: Int): Int = a + b
fun minus(a: Int, b: Int): Int = a - b
fun multi(a: Int, b: Int): Int = a * b
fun div(a: Int, b: Int): Int = a / b
